package tools

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

func SaveHtml(html io.Reader, name string) {
	str, _ := ioutil.ReadAll(html)
	file, _ := os.Create(name)
	re, err := io.WriteString(file, string(str))
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(re)
}

func GetChapterImg(dir string, url string, page string) (n int64, err error) {
	//判断目录是否存在
	TouchMangaDir(dir)

	//获取图片文件扩展名
	ext := GetImageExt(url)

	fileName := dir + page + "." + ext

	out, err := os.Create(fileName)

	defer out.Close()
	resp, err := http.Get(url)
	defer resp.Body.Close()
	pix, err := ioutil.ReadAll(resp.Body)
	n, err = io.Copy(out, bytes.NewReader(pix))

	return n, err
}

func GetCover(dir string, url string) (fileName string, err error) {
	//判断目录是否存在
	TouchMangaDir(dir)

	//获取图片文件扩展名
	var name string

	ext := GetImageExt(url)
	name = GetCoverName(dir, ext)

	fileName = dir + name

	out, err := os.Create(fileName)

	defer out.Close()
	resp, err := http.Get(url)
	defer resp.Body.Close()
	pix, err := ioutil.ReadAll(resp.Body)
	_, err = io.Copy(out, bytes.NewReader(pix))

	return fileName, err
}

//创建目录
func TouchMangaDir(dir string) {
	_, err := os.Stat(dir)
	if os.IsNotExist(err) {
		os.MkdirAll(dir, 0755)
	}
}

func GetImageExt(url string) string {
	res := strings.Split(url, ".")
	return res[len(res)-1]
}

func Md5(str string) string {
	h := md5.New()
	h.Write([]byte(str))

	return hex.EncodeToString(h.Sum(nil))
}

func GetCoverName(path string, ext string) string {
	str := strconv.FormatInt(time.Now().UnixNano(), 10) + strconv.FormatFloat(rand.Float64(), 'g', 30, 32)
	var name string
	for {
		name = Md5(str) + "." + ext
		_, err := os.Stat(path + name)
		if os.IsNotExist(err) {
			break
		}
	}
	return name
}

func FormatNo(no string) float64 {
	res, _ := strconv.ParseFloat(no, 64)
	return res
}

func ParseNo(no float64) string {
	res := strconv.FormatFloat(no, 'g', -1, 64)
	return res
}
